package com.suxin.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * @Classname SelectorClientTest
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/12/28 20:37
 * @Created by ASUS
 */
public class SelectorClientTest {

    public static void read(SocketChannel socketChannel) throws IOException {
        Selector selector = Selector.open();
        // 注册一个可读的事件
        socketChannel.register(selector, SelectionKey.OP_READ);
        // 客户端阻塞接收可读事件
        while (selector.select() != 0) {
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 可读事件
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer allocate = ByteBuffer.allocate(1024);
                    int len;
                    while ((len = channel.read(allocate)) != 0 && len != -1) {
                        allocate.limit(len - 1);
                        allocate.position(0);
                        System.out.println(" client server msg：--->" + new String(allocate.array()));
                        allocate.clear();
                    }
                } else if (selectionKey.isConnectable()) {
                    System.out.println("客户端与服务器已经建立成功....");
                }
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        socketChannel.connect(new InetSocketAddress(9000));
        while (!socketChannel.finishConnect()) {
            System.out.println("正在连接server...");
        }
        // 单独起一个线程 读操作
        new Thread(() -> {
            try {
                read(socketChannel);
                TimeUnit.SECONDS.sleep(1500);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        }
        socketChannel.close();
    }

}